/*
 * @Author: your name
 * @Date: 2021-08-04 14:53:25
 * @LastEditTime: 2021-08-08 17:02:38
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \niushop\src\http\index.js
 */
import axios from 'axios'
import Qs from 'qs'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
if(window.sessionStorage.token){
    axios.defaults.headers['authorization'] = window.sessionStorage.token;
}

//创建axios实例
let axiosObj = axios.create({
    baseURL: 'http://localhost:8888'
})

//请求拦截器
axiosObj.interceptors.request.use(config=>{
    return config
},err=>{
    return Promise.reject(err)
})

//响应拦截
axiosObj.interceptors.response.use(res=>{
    return res
},err=>{
    return Promise.reject(err)
})

//统一请求方法
async function http({method = 'get',path,params}){
    let result 
    if(method === 'get' || method === 'delete'){
        await axiosObj[method](path,{
            params
        }).then(res=>{
            result = res
        }).catch(err=>{
            result = err
        })
    }else if(method === 'post' || method === 'put' || method === 'patch'){
        let s=Qs.stringify(params)
        
        await axiosObj[method](path,s).then(res=>{
            result = res
        }).catch(err=>{
            result = err
        })
    }

    return result
}



export default http